﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;


namespace RFIDLIB
{
    public class TeaRfidHelper
    {
        public static UIntPtr hreader;
        public delegate void GetTagData(string UID);
        public static event GetTagData OngetTagData;
        public delegate void GetTagDatas(string UID);
        public static event GetTagDatas OngetTagDatas;
        public static bool IsReadEmployee;
        public const int RFID_SEEK_FIRST = 1;// Seek first
        static Thread InvenThread = null;
        static Thread WriteThread = null;
        static Thread readEmployee = null;
        public static bool _shouldStop = true;
        public static bool _shouldEmployee = true;
        public static bool _shouldStopWrite = true;
        public static string dataInfo;
        public static string tagtime;

        public static byte[] byteurl = new byte[] { };


        //连接读写器
        public static bool OpenTeaReader(string connstr)
        {
            bool result = false;
            try
            {

                
                int iret = RFIDLIB.rfidlib_reader.RDR_Open(connstr, ref hreader);
                if (iret == 0) result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                result = false;
            }
            return result;
        }
        //断开读写器
        public static bool CloseTeaReader()
        {
            bool result = false;
            try
            {
                int iret = RFIDLIB.rfidlib_reader.RDR_Close(hreader);
                if (iret == 0) result = true;
                if (InvenThread != null)
                {
                    InvenThread.Abort();
                }
            }
            catch
            { }
            return result;
        }
        //读取标签
        public static void ReadTeaTag()
        {
            while (!_shouldStop)
            {
                Byte AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;
                Byte AntennaSelCount = 0;
                byte[] AntennaSel = new byte[16];
                UInt32 nTagCount = 0;
                int iret;
                UIntPtr InvenParamSpecList = UIntPtr.Zero;
                InvenParamSpecList = RFIDLIB.rfidlib_reader.RDR_CreateInvenParamSpecList();
                if (InvenParamSpecList.ToUInt64() != 0)
                {
                    RFIDLIB.rfidlib_aip_iso15693.ISO15693_CreateInvenParam(InvenParamSpecList, 0, 0, 0, 0);
                }
                nTagCount = 0;

                iret = RFIDLIB.rfidlib_reader.RDR_TagInventory(hreader, AIType, AntennaSelCount, AntennaSel, InvenParamSpecList);
                if (iret == 0 || iret == -21)
                {
                    nTagCount += RFIDLIB.rfidlib_reader.RDR_GetTagDataReportCount(hreader);
                    UIntPtr TagDataReport;
                    TagDataReport = (UIntPtr)0;
                    TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_FIRST);
                    while (TagDataReport.ToUInt64() > 0)
                    {
                        UInt32 aip_id = 0;
                        UInt32 tag_id = 0;
                        UInt32 ant_id = 0;
                        Byte dsfid = 0;
                        Byte uidlen = 0;
                        Byte[] uid = new Byte[16];

                        iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ParseTagDataReport(TagDataReport, ref aip_id, ref tag_id, ref ant_id, ref dsfid, uid);
                        if (iret == 0)
                        {
                            uidlen = 8;
                            object[] pList = { aip_id, tag_id, ant_id, uid, (int)uidlen };
                            string strUid = BitConverter.ToString(uid, 0, (int)uidlen).Replace("-", string.Empty);
                            OngetTagData(strUid);
                        }
                        try
                        {
                            TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_NEXT); //next
                        }
                        catch (Exception err)
                        {
                            //LogHelper("读取茶标异常：", err);
                        }
                    }
                    if (iret == -21) // stop trigger occur,need to inventory left tags
                    {
                        AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;//use only-new-tag inventory 

                    }
                    iret = 0;
                }
                if (InvenParamSpecList.ToUInt64() != 0) RFIDLIB.rfidlib_reader.DNODE_Destroy(InvenParamSpecList);
            }
        }
        //写入标签
        public static void WriteTag()
        {
            while (!_shouldStopWrite)
            {
                Byte AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;
                Byte AntennaSelCount = 0;
                byte[] AntennaSel = new byte[16];
                UInt32 nTagCount = 0;
                int iret;
                UIntPtr InvenParamSpecList = UIntPtr.Zero;
                InvenParamSpecList = RFIDLIB.rfidlib_reader.RDR_CreateInvenParamSpecList();
                if (InvenParamSpecList.ToUInt64() != 0)
                {
                    RFIDLIB.rfidlib_aip_iso15693.ISO15693_CreateInvenParam(InvenParamSpecList, 0, 0, 0, 0);
                }
                nTagCount = 0;

                iret = RFIDLIB.rfidlib_reader.RDR_TagInventory(hreader, AIType, AntennaSelCount, AntennaSel, InvenParamSpecList);
                if (iret == 0 || iret == -21)
                {
                    nTagCount += RFIDLIB.rfidlib_reader.RDR_GetTagDataReportCount(hreader);
                    UIntPtr TagDataReport;
                    TagDataReport = (UIntPtr)0;
                    TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_FIRST);
                    while (TagDataReport.ToUInt64() > 0)
                    {
                        UInt32 aip_id = 0;
                        UInt32 tag_id = 0;
                        UInt32 ant_id = 0;
                        Byte dsfid = 0;
                        Byte uidlen = 0;
                        Byte[] uid = new Byte[16];

                        iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ParseTagDataReport(TagDataReport, ref aip_id, ref tag_id, ref ant_id, ref dsfid, uid);
                        if (iret == 0)
                        {
                            uidlen = 8;
                            object[] pList = { aip_id, tag_id, ant_id, uid, (int)uidlen };
                            string strUid = BitConverter.ToString(uid, 0, (int)uidlen).Replace("-", string.Empty);

                            byte[] uid1 = StringToByteArrayFastest(strUid);
                            Byte addrMode = (Byte)1;
                            UIntPtr hTag = (UIntPtr)0;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_Connect(hreader, RFIDLIB.rfidlib_def.RFID_ISO15693_PICC_ICODE_SLI_ID, addrMode, uid1, ref hTag);

                            string strs = Encrypt(strUid);
                            UInt32 blkAddr = (UInt32)02;                           
                            UInt32 numOfBlks = (UInt32)0;
                            if (byteurl.Length % 4 == 0)
                            {
                                numOfBlks =(UInt32) byteurl.Length / 4;
                            }
                            else
                            {
                                numOfBlks = (UInt32)(byteurl.Length / 4 + 1);
                            }
                            string strtowrite = "baidu.com";
                            var newbyteurl = new byte[8];
                            newbyteurl[0] = 225;
                            newbyteurl[1] = 64;
                            newbyteurl[2] = 16;
                            newbyteurl[3] = 01;
                            newbyteurl[4] = 03;
                            newbyteurl[5] = 14;
                            newbyteurl[6] = 209;
                            newbyteurl[7] = 01;

                            byte[] newBlksData = StringToByteArrayFastest(strtowrite);
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_WriteMultipleBlocks(hreader, hTag, blkAddr, numOfBlks, byteurl, (uint)byteurl.Length);
                            if (iret == 0)
                            {
                                OngetTagDatas(strUid);
                            }

                            var endbytes = new byte[4];
                            endbytes[0] = 254;
                            endbytes[1] = 00;
                            endbytes[2] = 00;
                            endbytes[3] = 00;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_WriteMultipleBlocks(hreader, hTag, blkAddr+numOfBlks, 1, endbytes, (uint)endbytes.Length);
                        }
                        TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_NEXT); //next
                    }
                    if (iret == -21) // stop trigger occur,need to inventory left tags
                    {
                        AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;//use only-new-tag inventory 

                    }
                    iret = 0;
                }
                if (InvenParamSpecList.ToUInt64() != 0) RFIDLIB.rfidlib_reader.DNODE_Destroy(InvenParamSpecList);
            }

        }
        //读取多块
        public static void ReadMulitTag()
        {
            try
            {
                while (!_shouldStop)
                {
                    Byte AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;
                    Byte AntennaSelCount = 0;
                    byte[] AntennaSel = new byte[16];
                    UInt32 nTagCount = 0;
                    int iret;
                    UIntPtr InvenParamSpecList = UIntPtr.Zero;
                    InvenParamSpecList = RFIDLIB.rfidlib_reader.RDR_CreateInvenParamSpecList();
                    if (InvenParamSpecList.ToUInt64() != 0)
                    {
                        RFIDLIB.rfidlib_aip_iso15693.ISO15693_CreateInvenParam(InvenParamSpecList, 0, 0, 0, 0);
                    }
                    nTagCount = 0;

                    iret = RFIDLIB.rfidlib_reader.RDR_TagInventory(hreader, AIType, AntennaSelCount, AntennaSel, InvenParamSpecList);
                    if (iret == 0 || iret == -21)
                    {
                        nTagCount += RFIDLIB.rfidlib_reader.RDR_GetTagDataReportCount(hreader);
                        UIntPtr TagDataReport;
                        TagDataReport = (UIntPtr)0;
                        TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_FIRST);
                        while (TagDataReport.ToUInt64() > 0)
                        {
                            UInt32 aip_id = 0;
                            UInt32 tag_id = 0;
                            UInt32 ant_id = 0;
                            Byte dsfid = 0;
                            Byte uidlen = 0;
                            Byte[] uid = new Byte[16];

                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ParseTagDataReport(TagDataReport, ref aip_id, ref tag_id, ref ant_id, ref dsfid, uid);
                            if (iret == 0)
                            {
                                uidlen = 8;
                                object[] pList = { aip_id, tag_id, ant_id, uid, (int)uidlen };
                                string strUid = BitConverter.ToString(uid, 0, (int)uidlen).Replace("-", string.Empty);

                                byte[] uid1 = StringToByteArrayFastest(strUid);
                                Byte addrMode = (Byte)1;
                                UIntPtr hTag = (UIntPtr)0;
                                iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_Connect(hreader, RFIDLIB.rfidlib_def.RFID_ISO15693_PICC_ICODE_SLI_ID, addrMode, uid1, ref hTag);

                                UInt32 bytesRead = 0;
                                UInt32 blockAddr = (UInt32)0;
                                UInt32 blockToRead = (UInt32)10;
                                UInt32 blocksRead = 0;
                                Byte[] BlockBuffer = new Byte[(blockToRead - blockAddr) * 4];
                                UInt32 nSize = (blockToRead - blockAddr) * 4;
                                iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ReadMultiBlocks(hreader, hTag, 0, blockAddr, blockToRead, ref blocksRead, BlockBuffer, nSize, ref bytesRead);

                                string str = BitConverter.ToString(BlockBuffer, 0, (int)bytesRead).Replace("-", string.Empty);
                                if (str != "")
                                {
                                    if (str.Length > 15 && str.Substring(2, 4) == "C8CB")
                                    {
                                        byte[] employee = new byte[8];
                                        Array.Copy(BlockBuffer, 8, employee, 0, 8);
                                        employee = GetByte(employee);
                                        string name = System.Text.Encoding.Unicode.GetString(employee);
                                        string cardNo = str.Substring(8, 8);
                                        str = cardNo + ":" + name;
                                    }
                                    OngetTagDatas(str + "," + strUid);
                                }
                            }
                            TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_NEXT); //next
                        }
                        if (iret == -21) // stop trigger occur,need to inventory left tags
                        {
                            AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;//use only-new-tag inventory 
                        }
                        iret = 0;
                    }
                    if (InvenParamSpecList.ToUInt64() != 0) RFIDLIB.rfidlib_reader.DNODE_Destroy(InvenParamSpecList);
                }
                RFIDLIB.rfidlib_reader.RDR_ResetCommuImmeTimeout(hreader);
            }
            catch (Exception err)
            {
                //LogHelper.WriteLog("读取标签信息异常：", err);
            }
        }
        //开始读取
        public static void StartTeaRead()
        {
            _shouldStop = false;
            InvenThread = new Thread(ReadMulitTag);
            InvenThread.Start();
        }
        public static bool ReaderStatus()
        {
            return !_shouldStop;
        }
        //停止读取
        public static void StopTeaRead()
        {
            try
            {
                _shouldStop = true;
                //RFIDLIB.rfidlib_reader.RDR_ResetCommuImmeTimeout(hreader);
                RFIDLIB.rfidlib_reader.RDR_SetCommuImmeTimeout(hreader);

            }
            catch (Exception err)
            {
                //LogHelper.WriteLog("停止读写器异常：", err);
            }
        }
        //开始写
        public static void StartTeaWrite()
        {
            _shouldStopWrite = false;
            WriteThread = new Thread(WriteTag);
            WriteThread.Start();
        }
        //停止写
        public static void StopTeaWrite()
        {
            _shouldStopWrite = true;
            RFIDLIB.rfidlib_reader.RDR_ResetCommuImmeTimeout(hreader);
        }

        /// <summary>
        /// 单次写入
        /// </summary>
        /// <returns></returns>
        public static bool Write()
        {
            try
            {
                Byte AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;
                Byte AntennaSelCount = 0;
                byte[] AntennaSel = new byte[16];
                UInt32 nTagCount = 0;
                int iret;
                UIntPtr InvenParamSpecList = UIntPtr.Zero;
                InvenParamSpecList = RFIDLIB.rfidlib_reader.RDR_CreateInvenParamSpecList();
                if (InvenParamSpecList.ToUInt64() != 0)
                {
                    RFIDLIB.rfidlib_aip_iso15693.ISO15693_CreateInvenParam(InvenParamSpecList, 0, 0, 0, 0);
                }
                nTagCount = 0;

                iret = RFIDLIB.rfidlib_reader.RDR_TagInventory(hreader, AIType, AntennaSelCount, AntennaSel, InvenParamSpecList);
                if (iret == 0 || iret == -21)
                {
                    nTagCount += RFIDLIB.rfidlib_reader.RDR_GetTagDataReportCount(hreader);
                    UIntPtr TagDataReport;
                    TagDataReport = (UIntPtr)0;
                    TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_FIRST);
                    while (TagDataReport.ToUInt64() > 0)
                    {
                        UInt32 aip_id = 0;
                        UInt32 tag_id = 0;
                        UInt32 ant_id = 0;
                        Byte dsfid = 0;
                        Byte uidlen = 0;
                        Byte[] uid = new Byte[16];

                        iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ParseTagDataReport(TagDataReport, ref aip_id, ref tag_id, ref ant_id, ref dsfid, uid);
                        if (iret == 0)
                        {
                            uidlen = 8;
                            object[] pList = { aip_id, tag_id, ant_id, uid, (int)uidlen };
                            string strUid = BitConverter.ToString(uid, 0, (int)uidlen).Replace("-", string.Empty);

                            byte[] uid1 = StringToByteArrayFastest(strUid);
                            Byte addrMode = (Byte)1;
                            UIntPtr hTag = (UIntPtr)0;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_Connect(hreader, RFIDLIB.rfidlib_def.RFID_ISO15693_PICC_ICODE_SLI_ID, addrMode, uid1, ref hTag);

                            string strs = Encrypt(strUid);
                            UInt32 blkAddr = (UInt32)02;
                            UInt32 numOfBlks = (UInt32)0;
                            if (byteurl.Length % 4 == 0)
                            {
                                numOfBlks = (UInt32)byteurl.Length / 4;
                            }
                            else
                            {
                                numOfBlks = (UInt32)(byteurl.Length / 4 + 1);
                            }
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_WriteMultipleBlocks(hreader, hTag, blkAddr, numOfBlks, byteurl, (uint)byteurl.Length);
                            if (iret == 0)
                            {
                                OngetTagDatas(strUid);
                            }

                            var endbytes = new byte[4];
                            endbytes[0] = 254;
                            endbytes[1] = 00;
                            endbytes[2] = 00;
                            endbytes[3] = 00;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_WriteMultipleBlocks(hreader, hTag, blkAddr + numOfBlks, 1, endbytes, (uint)endbytes.Length);
                        }
                        TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_NEXT); //next
                    }
                    if (iret == -21) // stop trigger occur,need to inventory left tags
                    {
                        AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;//use only-new-tag inventory 

                    }
                    iret = 0;
                }
                if (InvenParamSpecList.ToUInt64() != 0) RFIDLIB.rfidlib_reader.DNODE_Destroy(InvenParamSpecList);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        //初始化
        public static void IninTeaRead()
        {
            //加载设备驱动，只需启动一次
            RFIDLIB.rfidlib_reader.RDR_LoadReaderDrivers("\\Drivers");
        }

        //读取工号信息
        public static void StartEmployeeRead()
        {
            _shouldEmployee = false;
            readEmployee = new Thread(ReadEmployee);
            readEmployee.Start();
        }
        //停止读取
        public static void StopEmployeeRead()
        {
            _shouldEmployee = true;
            RFIDLIB.rfidlib_reader.RDR_ResetCommuImmeTimeout(hreader);
        }
        public static void ReadEmployee()
        {
            while (!_shouldEmployee)
            {
                Byte AIType = RFIDLIB.rfidlib_def.AI_TYPE_NEW;
                Byte AntennaSelCount = 0;
                byte[] AntennaSel = new byte[16];
                UInt32 nTagCount = 0;
                int iret;
                UIntPtr InvenParamSpecList = UIntPtr.Zero;
                InvenParamSpecList = RFIDLIB.rfidlib_reader.RDR_CreateInvenParamSpecList();
                if (InvenParamSpecList.ToUInt64() != 0)
                {
                    RFIDLIB.rfidlib_aip_iso15693.ISO15693_CreateInvenParam(InvenParamSpecList, 0, 0, 0, 0);
                }
                nTagCount = 0;

                iret = RFIDLIB.rfidlib_reader.RDR_TagInventory(hreader, AIType, AntennaSelCount, AntennaSel, InvenParamSpecList);
                if (iret == 0 || iret == -21)
                {
                    nTagCount += RFIDLIB.rfidlib_reader.RDR_GetTagDataReportCount(hreader);
                    UIntPtr TagDataReport;
                    TagDataReport = (UIntPtr)0;
                    TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_FIRST);
                    while (TagDataReport.ToUInt64() > 0)
                    {
                        UInt32 aip_id = 0;
                        UInt32 tag_id = 0;
                        UInt32 ant_id = 0;
                        Byte dsfid = 0;
                        Byte uidlen = 0;
                        Byte[] uid = new Byte[16];

                        iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ParseTagDataReport(TagDataReport, ref aip_id, ref tag_id, ref ant_id, ref dsfid, uid);
                        if (iret == 0)
                        {
                            uidlen = 8;
                            object[] pList = { aip_id, tag_id, ant_id, uid, (int)uidlen };
                            string strUid = BitConverter.ToString(uid, 0, (int)uidlen).Replace("-", string.Empty);

                            byte[] uid1 = StringToByteArrayFastest(strUid);
                            Byte addrMode = (Byte)1;
                            UIntPtr hTag = (UIntPtr)0;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_Connect(hreader, RFIDLIB.rfidlib_def.RFID_ISO15693_PICC_ICODE_SLI_ID, addrMode, uid1, ref hTag);

                            UInt32 bytesRead = 0;
                            UInt32 blockAddr = (UInt32)0;
                            UInt32 blockToRead = (UInt32)12;
                            UInt32 blocksRead = 0;
                            Byte[] BlockBuffer = new Byte[(blockToRead - blockAddr) * 4];
                            UInt32 nSize = (blockToRead - blockAddr) * 4;
                            iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ReadMultiBlocks(hreader, hTag, 0, blockAddr, blockToRead, ref blocksRead, BlockBuffer, nSize, ref bytesRead);

                            byte[] validateInfo = new byte[4];
                            byte[] employeeNo = new byte[4];
                            byte[] employee = new byte[8];
                            byte[] validateMd5 = new byte[32];
                            byte[] md5 = new byte[16];
                            Array.Copy(BlockBuffer, 0, validateInfo, 0, 4);
                            Array.Copy(BlockBuffer, 4, employeeNo, 0, 4);
                            Array.Copy(BlockBuffer, 8, employee, 0, 8);
                            Array.Copy(BlockBuffer, 0, validateMd5, 0, 32);
                            Array.Copy(BlockBuffer, 32, md5, 0, 16);

                            string validateCode = BitConverter.ToString(validateInfo, 0, validateInfo.Length).Replace("-", string.Empty);
                            if (validateCode.Length == 8 && validateCode.Substring(2, 4) == "C8CB")
                            {
                                //string tagMd5 = BitConverter.ToString(md5, 0, md5.Length).Replace("-", string.Empty);
                                //Util util = new Util();
                                //string getMd5 = util.MD5(BitConverter.ToString(validateMd5, 0, validateMd5.Length).Replace("-", string.Empty)).ToUpper();
                                //if (tagMd5 == getMd5)
                                //{
                                //    employee = GetByte(employee);
                                //    string name = System.Text.Encoding.Unicode.GetString(employee);
                                //    string str = BitConverter.ToString(employeeNo, 0, employeeNo.Length).Replace("-", string.Empty);
                                //    OngetTagData(str + "," + name);
                                //}
                            }

                        }
                        TagDataReport = RFIDLIB.rfidlib_reader.RDR_GetTagDataReport(hreader, RFIDLIB.rfidlib_def.RFID_SEEK_NEXT); //next
                    }
                    if (iret == -21) // stop trigger occur,need to inventory left tags
                    {
                        AIType = RFIDLIB.rfidlib_def.AI_TYPE_CONTINUE;//use only-new-tag inventory 

                    }
                    iret = 0;
                }
                if (InvenParamSpecList.ToUInt64() != 0) RFIDLIB.rfidlib_reader.DNODE_Destroy(InvenParamSpecList);
            }
        }
        public static byte[] GetByte(byte[] B)
        {
            for (int F = B.Length; --F > 0;)
            {
                byte T = B[F];
                B[F] = B[F - 1];
                B[--F] = T;
            }
            return B;
        }
        public static byte[] StringToByteArrayFastest(string hex)
        {
            if (hex.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            int len = hex.Length >> 1;
            byte[] arr = new byte[len];

            for (int i = 0; i < len; ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
            }

            return arr;
        }
        public static int GetHexVal(char hex)
        {
            int val = (int)hex;
            //For uppercase A-F letters:
            // return val - (val < 58 ? 48 : 55);
            //For lowercase a-f letters:
            //return val - (val < 58 ? 48 : 87);
            //Or the two combined, but a bit slower:
            return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
        }

        private static string Encrypt(string uid)
        {
            string result = "";
            try
            {
                //string productStr = dataInfo;
                //Util util = new Util();
                ////将（uid和productStr）做MD5
                //string s1 = util.MD5(uid + productStr);
                ////取S1的前8位，作为K1
                //string k1 = s1.Substring(0, 8);
                ////取当前时间戳T+K1做MD5作为K2
                //string T = getTime();
                //string k2 = util.MD5(T + k1);
                ////区k2的前16位得到k3
                //string k3 = k2.Substring(0, 16);
                ////以k3为秘钥使用HMACSHA1算法，摘要（uid+productstr）得到s2

                //string s2 = util.EncryptToSha1(uid + productStr, k3);
                ////将s2做MD5得到s3
                //string s3 = util.MD5(s2);
                ////取s3前24位得到s4
                //string s4 = s3.Substring(0, 24);
                ////k1为水印区1，s4位水印区2
                //string tag03 = productStr.Substring(0, 24);
                //string tag45 = k1;
                //string tag56 = productStr.Substring(24, 8);
                //string tag68 = s4;
                //result = tag03 + tag45 + tag56 + tag68;
                //tagtime = T;
            }
            catch (Exception err)
            {
                //LogHelper.WriteLog("赋码算法异常：", err);
            }
            return result;
        }
        private static string getTime()
        {
            TimeSpan times = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string timestamp = Convert.ToInt64(times.TotalMilliseconds).ToString();
            return timestamp;
        }

        public static bool Lock(string strUid)
        {
            bool isLocked = false;
            try
            {
                for (var s = 0; s < 3; s++)
                {
                    byte[] uid1 = StringToByteArrayFastest(strUid);
                    Byte addrMode = (Byte)1;
                    UIntPtr hTag = (UIntPtr)0;
                    int iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_Connect(hreader, RFIDLIB.rfidlib_def.RFID_ISO15693_PICC_ICODE_SLI_ID, addrMode, uid1, ref hTag);
                    if (iret == 0)
                    {
                        UInt32 bytesRead = 0;
                        UInt32 blockAddr = (UInt32)0;
                        UInt32 blockToRead = (UInt32)4;
                        UInt32 blocksRead = 0;
                        Byte[] BlockBuffer = new Byte[(blockToRead - blockAddr) * 5];
                        UInt32 nSize = (blockToRead - blockAddr) * 5;
                        iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_ReadMultiBlocks(hreader, hTag, 1, blockAddr, blockToRead, ref blocksRead, BlockBuffer, nSize, ref bytesRead);
                        if (iret == 0)
                        {
                            string str = BitConverter.ToString(BlockBuffer, 0, (int)bytesRead).Replace("-", string.Empty);
                            for (var i = 0; i < 2; i++)
                            {
                                if (str.Substring((i + 2) * 10, 2) == "00")
                                {
                                    UInt32 blkAddr = (UInt32)(i + 2);
                                    UInt32 numOfBlks = 1;
                                    iret = RFIDLIB.rfidlib_aip_iso15693.ISO15693_LockMultipleBlocks(hreader, hTag, blkAddr, numOfBlks);
                                    if (iret != 0)
                                    {
                                        //LogHelper.WriteLog("所失败：" + str.Length);
                                        isLocked = false;
                                        break;
                                    }
                                    else
                                    {
                                        isLocked = true;
                                    }
                                }
                                else
                                {
                                    isLocked = true;
                                }
                            }
                            if (isLocked)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //LogHelper.WriteLog("锁定标签异常：", err);
            }
            return isLocked;

        }
    }
}
